package com.yjd.comm.util;

import com.yjd.comm.enums.ApiRequestWayEnum;
import com.yjd.comm.user.dto.UserSession;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * <b>description</b>：用户身份认证工具 <br>
 */
public class UserAccessTokenUtil {
	/**
	 * 根据用户信息生成用户token对象
	 * 
	 * @param UserSession
	 * @return
	 * @throws Exception 
	 */
	public static String generateAccessToken(UserSession UserSession) throws Exception {
		return generateAccessToken(UserSession, null);
	}
	
	/**
	 * 根据用户信息生成用户token对象
	 * 
	 * @param userSession
	 * @param apw api请求方式
	 * @return
	 * @throws Exception 
	 */
	public static String generateAccessToken(UserSession userSession, ApiRequestWayEnum apw) throws Exception {
		if (userSession == null) {
			FrameUtil.throwBaseException1("用户对象不能为空!");
		}
		StringBuilder tokenOriginal = new StringBuilder();
		tokenOriginal.append(userSession.getUser_id()
				+ userSession.getPassword()
				+ userSession.getEncrypt()
				+ userSession.getLastMobileLoginTime()
				+ userSession.getMobile_number()
				+ userSession.getDevice_no()
				+ userSession.getIs_inuse());

		String token = DigestUtils.md5Hex(tokenOriginal.toString());
		return token;
	}

	/**
	 * 验证用户的令牌是否有效
	 * 
	 * @param UserSession
	 * @param token
	 * @return
	 * @throws Exception 
	 */
	public static boolean validToken(UserSession UserSession, String token, ApiRequestWayEnum apw) throws Exception {
		if (UserSession == null || StringUtil.isEmpty(token)) {
			FrameUtil.throwBaseException1("用户对象和token不能为空!");
		}
		return UserAccessTokenUtil.generateAccessToken(UserSession, apw).equals(token);
	}
}
